<template>
  <div>
    <!-- 搜索区域 -->
    <div style="margin-bottom: 20px">
      <el-input v-model="data.searchTitle" placeholder="请输入活动标题" style="width: 200px" clearable></el-input>
      <el-button type="primary" style="margin-left: 10px" @click="handleSearch">查询</el-button>
      <el-button type="primary" style="margin-left: 10px" @click="handleAdd">新增</el-button>
      <el-button type="danger" style="margin-left: 10px" :disabled="!data.multipleSelection.length" @click="delBatch">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column prop="id" label="ID" width="80" /> -->
      <el-table-column prop="title" label="活动标题" />
      <el-table-column prop="descr" label="活动介绍" show-overflow-tooltip />
      <el-table-column prop="activityType" label="活动类型" />
      <el-table-column prop="startTime" label="开始时间">
        <template #default="scope">
          {{ formatDate(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间">
        <template #default="scope">
          {{ formatDate(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="location" label="活动地点" />
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button
            v-if="!scope.row.clubId"
            type="warning"
            size="small"
            @click="fixActivityClubId(scope.row)"
          >
            修复社团
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="del(scope.row.id)"
          >
            删除
          </el-button>
          <el-button type="info" size="small" @click="handleViewApplications(scope.row)">审批报名</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div style="margin-top: 20px">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 表单对话框 -->
    <el-dialog v-model="data.formVisible" :title="data.dialogTitle" width="500px">
      <el-form :model="data.form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="data.form.title" placeholder="请输入活动标题"></el-input>
        </el-form-item>
        <el-form-item label="活动介绍" prop="descr">
          <el-input v-model="data.form.descr" type="textarea" placeholder="请输入活动介绍"></el-input>
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <el-select v-model="data.form.activityType" placeholder="请选择活动类型" style="width: 100%">
            <el-option label="学术讲座" value="学术讲座" />
            <el-option label="文艺演出" value="文艺演出" />
            <el-option label="体育比赛" value="体育比赛" />
            <el-option label="志愿服务" value="志愿服务" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
              v-model="data.form.startTime"
              type="date"
              placeholder="请选择开始日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
              v-model="data.form.endTime"
              type="date"
              placeholder="请选择结束日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="data.form.location" placeholder="请输入活动地点"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审批报名对话框 -->
    <el-dialog
      v-model="applicationDialogVisible"
      title="报名审批"
      width="60%"
    >
      <el-table :data="currentActivityApplications" stripe border>
        <el-table-column prop="studentName" label="学生姓名" width="120" />
        <el-table-column prop="contact" label="联系方式" width="150" />
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
              type="success"
              size="small"
              @click="handleApprove(scope.row)"
              :disabled="scope.row.status !== '待审核'"
            >通过</el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleReject(scope.row)"
              :disabled="scope.row.status !== '待审核'"
            >拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useRoute } from 'vue-router'
import axios from 'axios'
import President from './President.vue'

const route = useRoute()
const formRef = ref()
const user = JSON.parse(localStorage.getItem('xm-pro-user'))

// 数据
const data = reactive({
  form: {},
  tableData: [],
  total: 0,
  pageNum: 1,
  pageSize: 10,
  headerCellStyle: { background: '#f8f8f8', color: '#666' },
  formVisible: false,
  loading: false,
  dialogTitle: '',
  searchTitle: '',
  multipleSelection: [],
})

// 审批报名数据
const applicationDialogVisible = ref(false)
const currentActivityApplications = ref([])
const currentActivityId = ref(null)

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' }
  ],
  descr: [
    { required: true, message: '请输入活动介绍', trigger: 'blur' }
  ],
  activityType: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ]
}

// 获取用户的社团信息
const fetchUserClub = async () => {
  try {
    const response = await request.get(`/club/selectByPresidentId/${user.id}`)
    if (response.code === '200' && response.data && response.data.length > 0) {
      // 更新用户的 clubId
      user.clubId = response.data[0].id
      // 更新 localStorage 中的用户信息
      localStorage.setItem('xm-pro-user', JSON.stringify(user))
      return true
    }
    return false
  } catch (error) {
    console.error('获取社团信息失败:', error)
    return false
  }
}

// 获取数据
const load = () => {
  console.log(user.id);
  
  data.loading = true
  request.get('/activity/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.searchTitle,
      presidentId : user.id
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data.list
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg || '获取活动列表失败')
    }
  }).catch(err => {
    ElMessage.error('获取活动列表失败')
    console.error(err)
  }).finally(() => {
    data.loading = false
  })
}

// 搜索
const handleSearch = () => {
  data.pageNum = 1
  load()
}

// 分页
const handleSizeChange = (val) => {
  data.pageSize = val
  load()
}

const handleCurrentChange = (val) => {
  data.pageNum = val
  load()
}

// 新增
const handleAdd = async () => {
  if (!user || user.role !== 'PRE') {
    ElMessage.error('您不是社团社长，无法发布活动')
    return
  }

  // 如果没有 clubId，尝试获取
  if (!user.clubId) {
    const hasClub = await fetchUserClub()
    if (!hasClub) {
      ElMessage.error('您不是任何社团的社长，无法发布活动')
      return
    }
  }

  data.form = {
    clubId: user.clubId,
    title: '',
    descr: '',
    activityType: '',
    startTime: '',
    endTime: '',
    location: ''
  }
  data.formVisible = true
  data.dialogTitle = '新增活动'
}

// 编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
  data.dialogTitle = '编辑活动'
}

// 删除
const del = (id) => {
  ElMessageBox.confirm('确定删除该活动吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete(`/activity/deleteById/${id}`).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {
    // 用户取消
  })
}

// 批量删除
const delBatch = () => {
  if (data.multipleSelection.length === 0) {
    ElMessage.warning('请选择要删除的活动')
    return
  }
  ElMessageBox.confirm('确定批量删除这些活动吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/activity/deleteBatch', { data: data.multipleSelection.map(item => item.id) }).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg || '批量删除失败')
      }
    })
  }).catch(() => {
    // 用户取消
  })
}

// 表格多选
const handleSelectionChange = (val) => {
  data.multipleSelection = val
}

// 保存活动
const save = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (!user || user.role !== 'PRE') {
        ElMessage.error('您不是社团社长，无法发布活动')
        return
      }

      // 如果没有 clubId，尝试获取
      if (!user.clubId) {
        const hasClub = await fetchUserClub()
        if (!hasClub) {
          ElMessage.error('您不是任何社团的社长，无法发布活动')
          return
        }
      }

      if (data.form.id) {
        // 编辑时确保 clubId 不变
        request.put('/activity/updateById', {
          ...data.form,
          clubId: user.clubId
        }).then(res => {
          if (res.code === '200') {
            ElMessage.success('更新成功')
            data.formVisible = false
            load()
          } else {
            ElMessage.error(res.msg || '更新失败')
          }
        })
      } else {
        // 新增时设置 clubId
        request.post('/activity/add', {
          ...data.form,
          clubId: user.clubId
        }).then(res => {
          if (res.code === '200') {
            ElMessage.success('新增成功')
            data.formVisible = false
            load()
          } else {
            ElMessage.error(res.msg || '新增失败')
          }
        })
      }
    }
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = ('0' + (d.getMonth() + 1)).slice(-2)
  const day = ('0' + d.getDate()).slice(-2)
  const hours = ('0' + d.getHours()).slice(-2)
  const minutes = ('0' + d.getMinutes()).slice(-2)
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 查看报名列表
const handleViewApplications = async (row) => {
  currentActivityId.value = row.id
  try {
    // 使用完整的后端 URL  bypassing proxy
    const res = await axios.get(`http://localhost:8080/activityapplication/selectByActivityId/${row.id}`)
    if (res.data.code === '200') {
      currentActivityApplications.value = res.data.data || []
      applicationDialogVisible.value = true
    } else {
      ElMessage.error(res.data.msg || '获取报名列表失败')
    }
  } catch (err) {
    ElMessage.error('获取报名列表失败')
    console.error(err)
  }
}

// 审批报名
const handleApprove = async (application) => {
  try {
    const res = await request.put('/activityapplication/updateStatus', {
      id: application.id,
      status: '已通过'
    })
    if (res.code === '200') {
      ElMessage.success('审批成功')
      // 更新当前报名列表的状态
      application.status = '已通过'
    } else {
      ElMessage.error(res.msg || '审批失败')
    }
  } catch (err) {
    ElMessage.error('审批失败')
    console.error(err)
  }
}

// 拒绝报名
const handleReject = async (application) => {
  try {
    const res = await request.put('/activityapplication/updateStatus', {
      id: application.id,
      status: '已拒绝'
    })
    if (res.code === '200') {
      ElMessage.success('拒绝成功')
      // 更新当前报名列表的状态
      application.status = '已拒绝'
    } else {
      ElMessage.error(res.msg || '拒绝失败')
    }
  } catch (err) {
    ElMessage.error('拒绝失败')
    console.error(err)
  }
}

// 修复活动 clubId
const fixActivityClubId = async (activity) => {
  const user = JSON.parse(localStorage.getItem('xm-pro-user'))
  if (!user || !user.clubId) {
    ElMessage.error('您不是社团社长，无法修复活动')
    return
  }

  try {
    const response = await request.put('/activity/updateById', {
      ...activity,
      clubId: user.clubId
    })
    
    if (response.code === '200') {
      ElMessage.success('修复成功')
      load() // 重新加载活动列表
    } else {
      ElMessage.error(response.msg || '修复失败')
    }
  } catch (error) {
    console.error('修复活动失败:', error)
    ElMessage.error('修复活动失败')
  }
}

// 页面加载时获取数据
onMounted(async () => {
  // 如果是社长，先获取社团信息
  if (user && user.role === 'PRE' && !user.clubId) {
    await fetchUserClub()
  }
  load()
})
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 